import React, { useState, useEffect } from "react";
import { Page, useNavigate, useLocation } from "zmp-ui";
import { useI18n } from "../i18n";
import Navbar from "../components/navbar";
import { DeviceInfo } from "../api/types";
import { createZaloPayDeposit } from "../api/endpoints";

const CreateOrderPage: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const location = useLocation();
  
  const [deviceInfo, setDeviceInfo] = useState<DeviceInfo | null>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('zalopay');
  const [isProcessing, setIsProcessing] = useState(false);

  useEffect(() => {
    // 从路由状态中获取设备信息
    const device = location.state?.deviceInfo;
    if (device) {
      setDeviceInfo(device);
    } else {
      // 如果没有设备信息，返回扫码页面
      navigate('/scan');
    }
  }, [location.state, navigate]);

  // 处理支付
  const handlePayment = async () => {
    try {
      setIsProcessing(true);
      
      if (!deviceInfo) {
        alert(t('payment.deviceInfoMissing'));
        return;
      }

      // 调用ZaloPay押金支付接口
      const paymentResponse = await createZaloPayDeposit({
        deviceId: deviceInfo.id,
        powerBankType: deviceInfo.powerbankType
      });

      if (paymentResponse.code === 200 && paymentResponse.data) {
        // 在Zalo Mini App中，支付URL会直接跳转到ZaloPay支付页面
        // 支付完成后会通过回调处理结果
        try {
          // 打开ZaloPay支付页面
          window.open(paymentResponse.data, '_self');
          
          // 注意：在Zalo Mini App中，支付结果会通过回调接口处理
          // 这里我们假设支付成功，实际应该通过回调接口确认
          setTimeout(() => {
            // 模拟支付成功，实际应该通过回调接口确认
            navigate('/order-detail/success', {
              state: {
                orderInfo: {
                  orderId: paymentResponse.data,
                  amount: depositAmount,
                  deviceId: deviceInfo.id,
                  paymentTime: new Date().toISOString()
                }
              }
            });
          }, 3000);
          
        } catch (paymentError) {
          console.error('ZaloPay支付失败:', paymentError);
          alert(t('payment.paymentFailed'));
        }
      } else {
        alert(paymentResponse.msg || t('payment.createOrderFailed'));
      }
      
    } catch (error) {
      console.error('支付失败:', error);
      alert(t('payment.paymentFailed'));
    } finally {
      setIsProcessing(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  if (!deviceInfo) {
    return (
      <Page className="page" style={{ backgroundColor: '#F5F5F7', padding: 0 }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
          <Navbar title={t('payment.title')} />
        </div>
        <div style={{ padding: '20px', textAlign: 'center' }}>
          <div>{t('payment.loading')}</div>
        </div>
      </Page>
    );
  }

  const depositAmount = deviceInfo.originalData?.config?.securityFee || 250000;

  return (
    <Page className="page" style={{ backgroundColor: '#2C3E50', padding: 0 }}>
      {/* 顶部导航栏 */}
      <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
        {/* <Navbar title={t('payment.title')} /> */}
      </div>

      {/* 主要内容区域 */}
      <div style={{ 
        // padding: '20px',
        // minHeight: '100vh',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        {/* 白色卡片 */}
        <div style={{
          backgroundColor: '#fff',
        //   borderRadius: '16px',
          padding: '24px',
          width: '100%',
          // width: '100%',
          height: '100%',

        //   maxWidth: '400px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
        }}>
          {/* 押金充值标题 */}
          <div style={{
            fontSize: '18px',
            fontWeight: 'bold',
            color: '#333',
            textAlign: 'center',
            marginBottom: '20px'
          }}>
            {t('payment.depositRecharge')}
          </div>

          {/* 押金金额 */}
          <div style={{
            textAlign: 'center',
            marginBottom: '16px'
          }}>
            <span style={{
              fontSize: '32px',
              fontWeight: 'bold',
              color: '#FF6B35'
            }}>
              {depositAmount.toLocaleString()}
            </span>
            <span style={{
              fontSize: '16px',
              color: '#333',
              marginLeft: '4px'
            }}>
              ₫
            </span>
          </div>

          {/* 退款说明 */}
          <div style={{
            fontSize: '12px',
            color: '#666',
            lineHeight: '1.5',
            textAlign: 'center',
            marginBottom: '24px'
          }}>
            {t('payment.refundPolicy')}
          </div>

          {/* 分隔线 */}
          <div style={{
            height: '1px',
            backgroundColor: '#E5E5E5',
            marginBottom: '24px'
          }}></div>

          {/* 支付方式 */}
          <div style={{
            fontSize: '16px',
            fontWeight: 'bold',
            color: '#333',
            marginBottom: '16px'
          }}>
            {t('payment.paymentMethod')}
          </div>

          {/* MoMo支付选项 */}
          {/* <div 
            style={{
              display: 'flex',
              alignItems: 'center',
              padding: '12px',
              borderRadius: '8px',
              backgroundColor: selectedPaymentMethod === 'momo' ? '#FFF5F0' : 'transparent',
              cursor: 'pointer',
              marginBottom: '8px'
            }}
            onClick={() => setSelectedPaymentMethod('momo')}
          >
            <div style={{
              width: '32px',
              height: '32px',
              backgroundColor: '#D63384',
              borderRadius: '6px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: '12px'
            }}>
              <span style={{ color: '#fff', fontSize: '10px', fontWeight: 'bold' }}>
                mo mo
              </span>
            </div>
            <div style={{ flex: 1, fontSize: '14px', color: '#333' }}>
              MoMo
            </div>
            <div style={{
              width: '20px',
              height: '20px',
              borderRadius: '50%',
              backgroundColor: selectedPaymentMethod === 'momo' ? '#FF6B35' : 'transparent',
              border: selectedPaymentMethod === 'momo' ? 'none' : '2px solid #E5E5E5',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              {selectedPaymentMethod === 'momo' && (
                <div style={{
                  width: '8px',
                  height: '8px',
                  borderRadius: '50%',
                  backgroundColor: '#fff'
                }}></div>
              )}
            </div>
          </div> */}

          {/* ZaloPay支付选项 */}
          <div 
            style={{
              display: 'flex',
              alignItems: 'center',
              padding: '12px',
              borderRadius: '8px',
              backgroundColor: selectedPaymentMethod === 'zalopay' ? '#FFF5F0' : 'transparent',
              cursor: 'pointer',
              marginBottom: '24px'
            }}
            onClick={() => setSelectedPaymentMethod('zalopay')}
          >
            <div style={{
              width: '32px',
              height: '32px',
              backgroundColor: '#0068FF',
              borderRadius: '6px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: '12px'
            }}>
              <span style={{ color: '#fff', fontSize: '10px', fontWeight: 'bold' }}>
                Zalo pay
              </span>
            </div>
            <div style={{ flex: 1, fontSize: '14px', color: '#333' }}>
              ZaloPay
            </div>
            <div style={{
              width: '20px',
              height: '20px',
              borderRadius: '50%',
              backgroundColor: selectedPaymentMethod === 'zalopay' ? '#FF6B35' : 'transparent',
              border: selectedPaymentMethod === 'zalopay' ? 'none' : '2px solid #E5E5E5',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              {selectedPaymentMethod === 'zalopay' && (
                <div style={{
                  width: '8px',
                  height: '8px',
                  borderRadius: '50%',
                  backgroundColor: '#fff'
                }}></div>
              )}
            </div>
          </div>

          {/* 立即支付按钮 */}
          <button
            onClick={handlePayment}
            disabled={isProcessing}
            style={{
              width: '100%',
              height: '48px',
              backgroundColor: '#FF6B35',
              color: '#fff',
              border: 'none',
              borderRadius: '24px',
              fontSize: '16px',
              fontWeight: 'bold',
              cursor: isProcessing ? 'not-allowed' : 'pointer',
              opacity: isProcessing ? 0.7 : 1,
              transition: 'all 0.2s'
            }}
          >
            {isProcessing ? t('payment.processing') : t('payment.payNow')}
          </button>
        </div>
      </div>
    </Page>
  );
};

export default CreateOrderPage;
